package com.ruiysoft.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Date : 2018-05-17
 *
 * @author WenJialu
 */
public enum CollectionUtil {

	INSTANCE;

	private static final Logger LOGGER = LoggerFactory.getLogger(CollectionUtil.class);

	/**
	 * list截取   [fromIndex, toIndex)
	 * @param list
	 * @param fromIndex
	 * @param toIndex
	 * @param <T>
	 * @return
	 */
	public <T> List<T> subList(List<T> list, int fromIndex, int toIndex) {
		if (null == list
				    || list.isEmpty()
					|| 0 > fromIndex
					|| 0 > toIndex
					|| fromIndex > toIndex
					|| fromIndex >= list.size()) {
			return Collections.emptyList();
		}
		toIndex = toIndex > list.size() ? list.size() : toIndex;
		List<T> sub = list.subList(fromIndex, toIndex);
		List<T> subList = new ArrayList<>(sub);
		sub.clear(); // since sub is backed by one, this removes all sub-list items from one
		return subList;
	}



	/**
	 * 分割集合     //TODO  效率？
	 * @param collection
	 * @param everyNum   每个集合数量
	 * @param <T>
	 * @param <C>
	 * @return
	 */
	public <T, C extends Collection<T>> List<C> split(C collection, int everyNum){
		if (null == collection || collection.isEmpty() || 0 >= everyNum) {
			return Collections.emptyList();
		}
		int count = 0;
		List<C> resultList = new ArrayList<>();
		Iterator<T> iterator = collection.iterator();
		C splitCollection = createInstance(collection.getClass());
		if (null == splitCollection) {
			return Collections.emptyList();
		}
		while (iterator.hasNext()) {
			T next = iterator.next();
			if (null != next) {
				count ++;
				splitCollection.add(next);
			}
			//到达边界，清零计数，resultList.add(splitCollection) 并重新生成splitCollection
			if (count == everyNum || !iterator.hasNext()) {
				count = 0;
				resultList.add(splitCollection);
				splitCollection = createInstance(collection.getClass());
				if (null == splitCollection)
					break;
			}
		}
		return resultList;
	}

	private <T> T createInstance(Class<? extends Collection> clazz){
		T obj = null;
		try {
			obj = (T) Class.forName(clazz.getName()).newInstance();
		} catch (Exception e) {
			LOGGER.error(String.valueOf(e));
		} 
		return obj;
	}


}
